package com.nine.aspect;

import com.nine.anno.RedisLimitAnno;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Aspect
@Component
public class RedisLimitAspect {

    Object result = null;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private DefaultRedisScript<Long> redisScript;

    @PostConstruct
    public void init() {
        redisScript = new DefaultRedisScript<>();
        redisScript.setResultType(Long.class);
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("rateLimiter.lua")));
    }

    @Around("@annotation(com.nine.anno.RedisLimitAnno)")
    public Object around(ProceedingJoinPoint joinPoint) {
        log.info("环绕通知开始。。。。。。。。。");

        // 1.获取方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        // 2.获取方法上注解，存在则需要限制
        RedisLimitAnno annotation = method.getAnnotation(RedisLimitAnno.class);
        if (annotation != null) {
            String key = annotation.key();
            if (!StringUtils.hasText(key)) {
                throw new RuntimeException("key未设置，异常");
            }
            String className = method.getDeclaringClass().getName();
            String methodName = method.getName();
            // 3. 设置key
            String limitKey = key + "\t" + className + "\t" + methodName;
            log.info("设置的key值为：{}", limitKey);

            long limit = annotation.permitPerSecond();
            long expire = annotation.expire();

            List<String> keys = new ArrayList<>();
            keys.add(key);

            // 当前的执行次数
            Long count = redisTemplate.execute(redisScript, keys, String.valueOf(limit), String.valueOf(expire));
            log.info("已执行的count值为：{}", count);
            if (count != null && count == 0) {
                log.info("限流功能开启，key：{}", key);
                return annotation.msg();
            }
        }
        try {
            // 放行
            result = joinPoint.proceed();
        } catch (Throwable e) {
            log.info("环绕通知异常。。。。。。。。。");
            throw new RuntimeException(e);
        }
        log.info("环绕通知返回。。。。。。。。。");
        log.info("环绕通知结束。。。。。。。。。");
        return result;
    }

}
